

import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';

interface FormData {
  emailPhone: string;
  verificationCode: string;
  newPassword: string;
  confirmPassword: string;
}

interface FormErrors {
  emailPhone: string;
  verificationCode: string;
  newPassword: string;
  confirmPassword: string;
}

interface PasswordStrength {
  score: number;
  text: string;
  className: string;
}

const ForgotPasswordPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 表单数据状态
  const [formData, setFormData] = useState<FormData>({
    emailPhone: '',
    verificationCode: '',
    newPassword: '',
    confirmPassword: ''
  });

  // 表单错误状态
  const [formErrors, setFormErrors] = useState<FormErrors>({
    emailPhone: '',
    verificationCode: '',
    newPassword: '',
    confirmPassword: ''
  });

  // UI状态
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [countdownSeconds, setCountdownSeconds] = useState(0);
  const [passwordStrength, setPasswordStrength] = useState<PasswordStrength>({
    score: 0,
    text: '密码强度：请输入密码',
    className: 'text-text-secondary text-sm'
  });

  // 定时器引用
  const countdownTimerRef = useRef<number | null>(null);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 忘记密码';
    return () => {
      document.title = originalTitle;
    };
  }, []);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (countdownTimerRef.current) {
        clearInterval(countdownTimerRef.current);
      }
    };
  }, []);

  // 邮箱/手机号验证
  const validateEmailPhone = (value: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRegex = /^1[3-9]\d{9}$/;
    return emailRegex.test(value) || phoneRegex.test(value);
  };

  // 密码强度检测
  const checkPasswordStrength = (password: string): number => {
    let score = 0;
    
    if (password.length >= 8) score++;
    if (/[A-Za-z]/.test(password)) score++;
    if (/\d/.test(password)) score++;
    if (/[^A-Za-z\d]/.test(password)) score++;

    let strengthInfo: PasswordStrength;

    switch (score) {
      case 0:
      case 1:
        strengthInfo = {
          score,
          text: '密码强度：弱',
          className: 'text-danger text-sm'
        };
        break;
      case 2:
        strengthInfo = {
          score,
          text: '密码强度：中等',
          className: 'text-tertiary text-sm'
        };
        break;
      case 3:
      case 4:
        strengthInfo = {
          score,
          text: '密码强度：强',
          className: 'text-secondary text-sm'
        };
        break;
      default:
        strengthInfo = {
          score,
          text: '密码强度：请输入密码',
          className: 'text-text-secondary text-sm'
        };
    }

    setPasswordStrength(strengthInfo);
    return score;
  };

  // 显示错误信息
  const showError = (field: keyof FormErrors, message: string) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: message
    }));
  };

  // 隐藏错误信息
  const hideError = (field: keyof FormErrors) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: ''
    }));
  };

  // 开始验证码倒计时
  const startCountdown = () => {
    setCountdownSeconds(60);
    
    countdownTimerRef.current = window.setInterval(() => {
      setCountdownSeconds(prev => {
        if (prev <= 1) {
          if (countdownTimerRef.current) {
            clearInterval(countdownTimerRef.current);
            countdownTimerRef.current = null;
          }
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  // 处理输入变化
  const handleInputChange = (field: keyof FormData, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));

    // 实时验证
    if (field === 'verificationCode') {
      const numericValue = value.replace(/\D/g, '');
      setFormData(prev => ({
        ...prev,
        [field]: numericValue
      }));
      if (numericValue.length === 6) {
        hideError(field);
      }
    }

    if (field === 'newPassword') {
      const score = checkPasswordStrength(value);
      if (value && score < 2) {
        showError(field, '密码长度至少8位，包含字母和数字');
      } else {
        hideError(field);
      }
      
      // 如果确认密码已输入，重新验证
      if (formData.confirmPassword) {
        if (value !== formData.confirmPassword) {
          showError('confirmPassword', '两次输入的密码不一致');
        } else {
          hideError('confirmPassword');
        }
      }
    }
  };

  // 处理输入框失去焦点
  const handleInputBlur = (field: keyof FormData) => {
    const value = formData[field].trim();

    switch (field) {
      case 'emailPhone':
        if (value && !validateEmailPhone(value)) {
          showError(field, '请输入有效的邮箱或手机号');
        } else {
          hideError(field);
        }
        break;
      case 'verificationCode':
        if (value && value.length !== 6) {
          showError(field, '请输入6位验证码');
        } else {
          hideError(field);
        }
        break;
      case 'confirmPassword':
        if (value && value !== formData.newPassword) {
          showError(field, '两次输入的密码不一致');
        } else {
          hideError(field);
        }
        break;
    }
  };

  // 发送验证码
  const handleSendCode = () => {
    const emailPhone = formData.emailPhone.trim();
    
    if (!emailPhone) {
      showError('emailPhone', '请先输入邮箱或手机号');
      return;
    }
    
    if (!validateEmailPhone(emailPhone)) {
      showError('emailPhone', '请输入有效的邮箱或手机号');
      return;
    }
    
    hideError('emailPhone');
    
    // 模拟发送验证码
    console.log('发送验证码到：', emailPhone);
    startCountdown();
    
    // 显示成功提示
    alert('验证码已发送，请查收');
  };

  // 表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const { emailPhone, verificationCode, newPassword, confirmPassword } = formData;
    let hasError = false;
    
    // 验证邮箱/手机号
    if (!emailPhone.trim()) {
      showError('emailPhone', '请输入邮箱或手机号');
      hasError = true;
    } else if (!validateEmailPhone(emailPhone.trim())) {
      showError('emailPhone', '请输入有效的邮箱或手机号');
      hasError = true;
    } else {
      hideError('emailPhone');
    }
    
    // 验证验证码
    if (!verificationCode.trim()) {
      showError('verificationCode', '请输入验证码');
      hasError = true;
    } else if (verificationCode.length !== 6) {
      showError('verificationCode', '请输入6位验证码');
      hasError = true;
    } else {
      hideError('verificationCode');
    }
    
    // 验证新密码
    if (!newPassword) {
      showError('newPassword', '请输入新密码');
      hasError = true;
    } else if (checkPasswordStrength(newPassword) < 2) {
      showError('newPassword', '密码长度至少8位，包含字母和数字');
      hasError = true;
    } else {
      hideError('newPassword');
    }
    
    // 验证确认密码
    if (!confirmPassword) {
      showError('confirmPassword', '请确认新密码');
      hasError = true;
    } else if (newPassword !== confirmPassword) {
      showError('confirmPassword', '两次输入的密码不一致');
      hasError = true;
    } else {
      hideError('confirmPassword');
    }
    
    if (hasError) {
      return;
    }
    
    // 模拟重置密码请求
    setIsSubmitting(true);
    
    setTimeout(() => {
      console.log('密码重置成功');
      setShowSuccessModal(true);
      setIsSubmitting(false);
    }, 1500);
  };

  // 处理成功模态框确认
  const handleSuccessOk = () => {
    setShowSuccessModal(false);
    navigate('/login');
  };

  // 处理返回登录
  const handleBackToLogin = () => {
    navigate(-1);
  };

  // 获取密码强度条样式
  const getStrengthBarClass = (index: number): string => {
    const baseClass = 'flex-1 h-1 rounded';
    if (passwordStrength.score >= index + 1) {
      if (passwordStrength.score <= 1) return `${baseClass} ${styles.passwordStrengthWeak}`;
      if (passwordStrength.score === 2) return `${baseClass} ${styles.passwordStrengthMedium}`;
      return `${baseClass} ${styles.passwordStrengthStrong}`;
    }
    return `${baseClass} bg-gray-200`;
  };

  return (
    <div className={styles.pageWrapper}>
      <div className="w-full max-w-md mx-auto px-4 py-8">
        {/* Logo和产品名称 */}
        <div className="text-center mb-8">
          <div className="w-16 h-16 bg-primary rounded-xl flex items-center justify-center mx-auto mb-4">
            <i className="fas fa-utensils text-white text-2xl"></i>
          </div>
          <h1 className="text-2xl font-bold text-text-primary">食算</h1>
          <p className="text-text-secondary mt-2">健康饮食，从计算开始</p>
        </div>

        {/* 忘记密码表单 */}
        <div className="bg-white rounded-2xl shadow-card p-8">
          <div className="text-center mb-8">
            <h2 className="text-xl font-semibold text-text-primary mb-2">重置密码</h2>
            <p className="text-text-secondary">请输入您的邮箱或手机号，我们将发送验证码帮助您重置密码</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* 邮箱/手机号输入 */}
            <div className="space-y-2">
              <label htmlFor="email-phone" className="block text-sm font-medium text-text-primary">
                邮箱/手机号 *
              </label>
              <input
                type="text"
                id="email-phone"
                name="email-phone"
                value={formData.emailPhone}
                onChange={(e) => handleInputChange('emailPhone', e.target.value)}
                onBlur={() => handleInputBlur('emailPhone')}
                className={`w-full px-4 py-3 border rounded-lg ${styles.formInputFocus} ${
                  formErrors.emailPhone ? 'border-danger' : 'border-border-light'
                }`}
                placeholder="请输入邮箱或手机号"
                required
              />
              {formErrors.emailPhone && (
                <div className="text-danger text-sm">
                  <i className="fas fa-exclamation-circle mr-1"></i>
                  <span>{formErrors.emailPhone}</span>
                </div>
              )}
            </div>

            {/* 验证码输入 */}
            <div className="space-y-2">
              <label htmlFor="verification-code" className="block text-sm font-medium text-text-primary">
                验证码 *
              </label>
              <div className="flex space-x-3">
                <input
                  type="text"
                  id="verification-code"
                  name="verification-code"
                  value={formData.verificationCode}
                  onChange={(e) => handleInputChange('verificationCode', e.target.value)}
                  onBlur={() => handleInputBlur('verificationCode')}
                  className={`flex-1 px-4 py-3 border rounded-lg ${styles.formInputFocus} ${
                    formErrors.verificationCode ? 'border-danger' : 'border-border-light'
                  }`}
                  placeholder="请输入验证码"
                  maxLength={6}
                  required
                />
                <button
                  type="button"
                  onClick={handleSendCode}
                  disabled={countdownSeconds > 0}
                  className={`px-6 py-3 rounded-lg whitespace-nowrap ${
                    countdownSeconds > 0
                      ? styles.btnDisabled
                      : 'bg-primary text-white hover:bg-indigo-600 transition-colors'
                  }`}
                >
                  {countdownSeconds > 0 ? `${countdownSeconds}秒后重发` : '发送验证码'}
                </button>
              </div>
              {formErrors.verificationCode && (
                <div className="text-danger text-sm">
                  <i className="fas fa-exclamation-circle mr-1"></i>
                  <span>{formErrors.verificationCode}</span>
                </div>
              )}
            </div>

            {/* 新密码输入 */}
            <div className="space-y-2">
              <label htmlFor="new-password" className="block text-sm font-medium text-text-primary">
                新密码 *
              </label>
              <div className="relative">
                <input
                  type={showNewPassword ? 'text' : 'password'}
                  id="new-password"
                  name="new-password"
                  value={formData.newPassword}
                  onChange={(e) => handleInputChange('newPassword', e.target.value)}
                  onBlur={() => handleInputBlur('newPassword')}
                  className={`w-full px-4 py-3 pr-12 border rounded-lg ${styles.formInputFocus} ${
                    formErrors.newPassword ? 'border-danger' : 'border-border-light'
                  }`}
                  placeholder="请输入新密码"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowNewPassword(!showNewPassword)}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                >
                  <i className={`fas ${showNewPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                </button>
              </div>
              {/* 密码强度指示器 */}
              <div className="space-y-2">
                <div className="flex space-x-1">
                  <div className={getStrengthBarClass(0)}></div>
                  <div className={getStrengthBarClass(1)}></div>
                  <div className={getStrengthBarClass(2)}></div>
                </div>
                <p className={passwordStrength.className}>{passwordStrength.text}</p>
              </div>
              {formErrors.newPassword && (
                <div className="text-danger text-sm">
                  <i className="fas fa-exclamation-circle mr-1"></i>
                  <span>{formErrors.newPassword}</span>
                </div>
              )}
            </div>

            {/* 确认密码输入 */}
            <div className="space-y-2">
              <label htmlFor="confirm-password" className="block text-sm font-medium text-text-primary">
                确认新密码 *
              </label>
              <div className="relative">
                <input
                  type={showConfirmPassword ? 'text' : 'password'}
                  id="confirm-password"
                  name="confirm-password"
                  value={formData.confirmPassword}
                  onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
                  onBlur={() => handleInputBlur('confirmPassword')}
                  className={`w-full px-4 py-3 pr-12 border rounded-lg ${styles.formInputFocus} ${
                    formErrors.confirmPassword ? 'border-danger' : 'border-border-light'
                  }`}
                  placeholder="请再次输入新密码"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                >
                  <i className={`fas ${showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                </button>
              </div>
              {formErrors.confirmPassword && (
                <div className="text-danger text-sm">
                  <i className="fas fa-exclamation-circle mr-1"></i>
                  <span>{formErrors.confirmPassword}</span>
                </div>
              )}
            </div>

            {/* 操作按钮 */}
            <div className="space-y-4 pt-4">
              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full py-3 bg-primary text-white rounded-lg hover:bg-indigo-600 transition-colors font-medium disabled:opacity-50"
              >
                {isSubmitting ? '重置中...' : '重置密码'}
              </button>
              
              <div className="text-center">
                <button
                  type="button"
                  onClick={handleBackToLogin}
                  className="text-primary hover:text-indigo-600 text-sm font-medium"
                >
                  <i className="fas fa-arrow-left mr-1"></i>
                  返回登录
                </button>
              </div>
            </div>
          </form>
        </div>

        {/* 成功提示模态框 */}
        {showSuccessModal && (
          <div 
            className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
            onClick={(e) => {
              if (e.target === e.currentTarget) {
                handleSuccessOk();
              }
            }}
          >
            <div className="bg-white rounded-2xl p-8 max-w-sm mx-4 text-center">
              <div className="w-16 h-16 bg-secondary bg-opacity-10 rounded-full flex items-center justify-center mx-auto mb-4">
                <i className="fas fa-check text-secondary text-2xl"></i>
              </div>
              <h3 className="text-lg font-semibold text-text-primary mb-2">密码重置成功</h3>
              <p className="text-text-secondary mb-6">您的密码已成功重置，请使用新密码登录</p>
              <button
                onClick={handleSuccessOk}
                className="w-full py-3 bg-primary text-white rounded-lg hover:bg-indigo-600 transition-colors"
              >
                去登录
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ForgotPasswordPage;

